const WebSocket = require('ws');
const readline = require('readline');
// Create a WebSocket server
const wss = new WebSocket.Server({ port: 8080 });
// Setup readline to read from console
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', (input) => {
    console.log(`You entered: ${input}`);

    // Broadcast the input to all connected WebSocket clients
    wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(`Server received: ${input}`);
        }
    });
});

wss.on('connection', (ws) => {
    console.log('New client connected!');

    // Send a message to the client
    ws.send('Welcome to the WebSocket server!');
    // Handle incoming messages from the client
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
        ws.send(`You said: ${message}`);
    });

    // Handle client disconnection
    ws.on('close', () => {
        console.log('Client disconnected.');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');